/**
 *  编辑页
 *
 * 作者 admin
 * 日期 2024-08-20 15:49:12
 */
layui.use(['jquery','febs', 'form', 'validate','fileUpload','autocomplete'], function () {
    var $ = layui.$,
        febs = layui.febs,
        layer = layui.layer,
        form = layui.form,
        laydate = layui.laydate,
        commonJs = layui.commonJS,
        fileUpload = layui.fileUpload,
        autocomplete = layui.autocomplete,
        $view = $('#hazardExamineRecord-edit'),
        $hazardOperation = $view.find('#hazardOperation'),
        $rectificationFlg = $view.find('#rectificationFlg'),
        $leaderUserSelect = $('#leaderUserSelect'),
        tableIns,
        teamUserTableIns,
        validate = layui.validate;

    let rectifyReturnRecordList=[];
    let teamUserList=[];

    let tenantId = POPUP_DATA.tenantId;
    let examineId = POPUP_DATA.examineId;
    let examineObjectId = POPUP_DATA.examineObjectId;
    let examineRecordId = POPUP_DATA.examineRecordId;

    initDictItemSelect();
    initFormValue();
    initGroupUserTable();
    form.verify(validate);
    form.render();
    laydate.render({
        elem: "#rectificationDeadline",
        done: function (value, date) {},
        type: 'date'
    })
    function initDictItemSelect(){
        //事故类型
        febs.initDictItemSelect($hazardOperation,'SAFETY_ACCIDENT_TYPE',hazardExamineRecordData.hazardOperation,null);
    }

    $('#inputAutoLeader').autocomplete({
        serviceUrl: ctx + 'common/user/list',//测试接口
        paramName:'keywords',
        useType:'user',
        params:{ tenantId: tenantId},
        onSelect: function(suggestion) {
            setLeaderUserAndDeptAttr(suggestion);
        },
    });

    var fileUploadDiv = fileUpload.render({
        elem: '#fileUpload',
        url: ctx + 'hazard/upload',
        type: 0,//0-图片，1-视频，2-其他
        maxNum:5,
        defaultData: getFileList(),
        done: function (res) {
        },
    });

    function getFileList() {
        if (hazardExamineRecordData.examineFileList && hazardExamineRecordData.examineFileList.length>0) {
            return  hazardExamineRecordData.examineFileList;
        }else {
            return  [];
        }
    }

    function initGroupUserTable() {
        teamUserTableIns = febs.table.init({
            elem: $view.find('#groupUserTable'),
            id: 'groupUserTable',
            page:false,
            skin: '',
            limit:Number.MAX_VALUE,
            cols: [[
                {title: '序号', type: 'numbers',width: 60},
                {field: 'teamName',title: '分组名称', minWidth: 220},
                {field: 'teamUserList', title: '检查人员', minWidth: 500, templet: function (d) {
                        var flg = '';
                        var users = d.teamUserList;
                        if(users){
                            users.forEach((item, index)=> {
                                flg += '<span class="layui-badge febs-bg-orange" style="margin-left:5px; ">'+item.realName+'</span>'
                            })
                        }
                        return flg;
                    }
                },
            ]],
            done: function(res, curr, count){
            },
            data:teamUserList
        });
    }


    initRectifyReturnTable();
    function initRectifyReturnTable() {
        tableIns = febs.table.init({
            elem: $view.find("#rectifyReturnTable"),
            id: 'rectifyReturnTable',
            page:false,
            skin: '',
            limit:Number.MAX_VALUE,
            cols: [[
                {title: '序号', type: 'numbers',width: 60},
                {field: 'returnRealName',align:'center', title: '退回人姓名', width: 100},
                {field: 'returnReason', title: '退回理由', minWidth: 260},
                {field: 'createdTime',align:'center', title: '退回时间', width: 180},
            ]],
            done: function(res, curr, count){
            },
            data:rectifyReturnRecordList
        });
    }

    function initFormValue() {
        if (hazardExamineRecordData) {
            if(hazardExamineRecordData.rectifyReturnRecordList && hazardExamineRecordData.rectifyReturnRecordList.length>0){
                rectifyReturnRecordList = hazardExamineRecordData.rectifyReturnRecordList;
            }
            if(hazardExamineRecordData.teamUserList && hazardExamineRecordData.teamUserList.length>0){
                teamUserList = hazardExamineRecordData.teamUserList;
            }
            if(hazardExamineRecordData.examineRecordId){
                $("#recordDeptNameDiv").text(hazardExamineRecordData.leaderDeptName);
                $("#leaderUserNoDiv").text(hazardExamineRecordData.leaderNo);
            }
            initProjectAreaId(hazardExamineRecordData.projectId);
            if(hazardExamineRecordData.rectificationFlg === '0'){
                //无需整改
                $("#rectificationFlg").removeAttr("checked");
                $view.find('div[name=ifShow]').addClass('febs-hide');
            }else{
                //待整改
                $("#rectificationFlg").attr("checked","true");
                $view.find('div[name=ifShow]').removeClass('febs-hide');
            }
            form.val("hazardExamineRecord-edit-form", {
                "examineRecordId": hazardExamineRecordData.examineRecordId,
                "tenantId": hazardExamineRecordData.tenantId,
                "examineId": hazardExamineRecordData.examineId,
                "hazardExamineTitle": hazardExamineRecordData.hazardExamineTitle,
                "hazardOperation": hazardExamineRecordData.hazardOperation,
                "hazardLevel": hazardExamineRecordData.hazardLevel,
                "areaId": hazardExamineRecordData.areaId,
                "areaName": hazardExamineRecordData.areaName,
                "examineEvidence": hazardExamineRecordData.examineEvidence,
                "projectId": hazardExamineRecordData.projectId,
                "projectName": hazardExamineRecordData.projectName,
                "leaderDeptId": hazardExamineRecordData.leaderDeptId,
                "leaderDeptName": hazardExamineRecordData.leaderDeptName,
                "leaderId": hazardExamineRecordData.leaderId,
                "leaderName": hazardExamineRecordData.leaderName,
                "leaderNo": hazardExamineRecordData.leaderNo,
                "questionDescription": hazardExamineRecordData.questionDescription,
                "rectificationDeadline": hazardExamineRecordData.rectificationDeadline,
                "rectificationRequire": hazardExamineRecordData.rectificationRequire,
                "feedbackContent": hazardExamineRecordData.feedbackContent,
                "feedbackDate": hazardExamineRecordData.feedbackDate,
                "auditUserId": hazardExamineRecordData.auditUserId,
                "auditRealName": hazardExamineRecordData.auditRealName,
                "auditRemark": hazardExamineRecordData.auditRemark,
                "auditDate": hazardExamineRecordData.auditDate,
                "status": hazardExamineRecordData.status,
                "recordUserId": hazardExamineRecordData.recordUserId,
                "recordRealName": hazardExamineRecordData.recordRealName,
                "recordDate": hazardExamineRecordData.recordDate,
                "examineFileList": hazardExamineRecordData.examineFileList,
            });
            form.render('checkbox');
        }
    }

    $leaderUserSelect.on('click', function () {
        febs.modal.open('责任人选择', 'common/user', {
            btn: ['确认','关闭'],
            area: $(window).width() <= 750 ? ['95%', '85%']: ['80%', '85%'],
            data:{
                tenantId:tenantId,
                multiple:false,
            },
            yes: function (index, layero) {
                let selectData = null
                if(typeof getSelectData  === 'function'){
                    selectData = getSelectData()
                }
                setLeaderUserAndDeptAttr(selectData);
                layer.close(index);
            },
            btn2: function (index, layero) {
                layer.close(index);
                return false;
            }
        });
    });
    function setLeaderUserAndDeptAttr(selectData){
        $view.find("input[name=leaderDeptId]").val(selectData.deptId);
        $view.find("input[name=leaderDeptName]").val(selectData.deptName);
        $("#recordDeptNameDiv").text(selectData.deptName);
        $view.find("#recordDeptNameDiv").text(selectData.deptName);
        $view.find("input[name=leaderId]").val(selectData.userId);
        $view.find("input[name=leaderName]").val(selectData.uname);
        $view.find("input[name=leaderNo]").val(selectData.userNo);
        $("#leaderUserNoDiv").text(selectData.userNo);
    }

    function reSetLeaderUserAndDeptAttr(selectData){
        $view.find("input[name=leaderDeptId]").val('');
        $view.find("input[name=leaderDeptName]").val('');
        $("#recordDeptNameDiv").text('');
        $view.find("#recordDeptNameDiv").text('');
        $view.find("input[name=leaderId]").val('');
        $view.find("input[name=leaderName]").val('');
        $view.find("input[name=leaderNo]").val('');
        $("#leaderUserNoDiv").text('');
        $("#rectificationDeadline").val('');
    }

    form.on('submit(hazardExamineRecord-edit-form-save)', function (data) {
        //待整改指派
        data.field.status = '1';
        addOrUpdate(data.field,'保存');
        return false;
    });

    form.on('submit(hazardExamineRecord-edit-form-submit)', function (data) {
        //检查记录status
        if($rectificationFlg.is(':checked')){
            if(commonJs.isEmpty($view.find("input[name=leaderName]").val())){
                febs.alert.warn('请选择责任人');
                return false;
            }
            //待整改
            data.field.status = '2';
        }else {
            //无需整改，流转的待审核状态
            data.field.status = '4';
        }
        addOrUpdate(data.field,'提交');
        return false;
    });

    form.on('switch(rectificationFlg)', function(data){
        var status = data.elem.checked;
        if(!status){
            //无需整改
            $view.find('div[name=ifShow]').addClass('febs-hide');
            reSetLeaderUserAndDeptAttr();
            $view.find('input[name="rectificationDeadline"]').attr("lay-verify","");
            $view.find('textarea[name="rectificationRequire"]').attr("lay-verify","");
            $view.find('textarea[name="questionDescription"]').attr("lay-verify","");
            $view.find('#rectificationDeadline-label').removeClass("febs-form-item-require");
            $view.find('#rectificationRequire-label').removeClass("febs-form-item-require");
            $view.find('#questionDescription-label').removeClass("febs-form-item-require");
            $view.find('#leaderName-label').removeClass("febs-form-item-require");
        }else{
            //待整改
            $view.find('div[name=ifShow]').removeClass('febs-hide');
            $view.find('input[name="rectificationDeadline"]').attr("lay-verify","required");
            $view.find('textarea[name="rectificationRequire"]').attr("lay-verify","required");
            $view.find('textarea[name="questionDescription"]').attr("lay-verify","required");
            $view.find('#rectificationDeadline-label').addClass("febs-form-item-require");
            $view.find('#rectificationRequire-label').addClass("febs-form-item-require");
            $view.find('#questionDescription-label').addClass("febs-form-item-require");
            $view.find('#leaderName-label').addClass("febs-form-item-require");
        }
    });

    form.on('select(projectId)', function(obj){
        // 获取选中项 value
        var projectId = obj.value;
        var selectProject = $view.find("select[name='projectId']").find("option:selected");
        if(projectId == ''){
            $("#areaId").empty();
            $view.find('input[name="projectName"]').val("");
            $view.find('input[name="projectLeaderId"]').val("");
            $view.find('input[name="projectLeaderName"]').val("");
        }else {
            initProjectAreaId(projectId);
            $view.find('input[name="projectName"]').val(selectProject.text());
            $view.find('input[name="projectLeaderId"]').val(selectProject.attr("projectManageId"));
            $view.find('input[name="projectLeaderName"]').val(selectProject.attr("projectManageName"));
        }
        form.render();
    });

    form.on('select(areaId)', function(obj){
        var areaId = obj.value;
        // 获取选中项 value
        var areaName = $view.find("select[name='areaId']").find("option:selected").text();
        if(areaId == ''){
            $view.find('input[name="areaName"]').val("");
        }else {
            $view.find('input[name="areaName"]').val(areaName);
        }
        form.render();
    });

    function initProjectAreaId(projectId) {
        if(projectId){
            //初始化项目区域
            var data ={
                tenantId:POPUP_DATA.tenantId,
                projectId:projectId
            };
            $("#areaId").empty();
            febs.getSync(ctx + 'baseProjectArea', data, function (r) {
                var resultData = r.data;
                var options = '<option value="">请选择</option>';
                $.each(resultData, function (index, item) {
                    options += '<option value="' + item.areaId + '">' + item.areaName + '</option>'
                })
                $("#areaId").append(options);
            });
        }

    }


    function addOrUpdate(data,operation) {
        data.tenantId = tenantId;
        data.examineId = examineId;
        data.examineRecordId = examineRecordId;
        data.examineObjectId = examineObjectId;

        var fileList = getImgData();
        data.examineFileList=fileList;
        //安全检查发布hazard_examine-status
        data.examineStatus='3';
        data.rectificationFlg = $rectificationFlg.is(':checked')?'1':'0';

        data.areaName = $("#areaId").find("option:selected").text().trim();
        data.projectName = $("#projectId").find("option:selected").text().trim();

        if (data.examineRecordId && data.examineRecordId.length > 0) {
            febs.modal.confirm(operation+'信息','确定'+operation+'信息？', function (index) {
                febs.postArray(ctx + 'hazardExamineRecord/update', data, function () {
                    layer.closeAll();
                    febs.alert.success('提交成功');
                    $('#febs-hazardExamineRecord').find('#query').trigger('click');
                });
            });

        } else {
            febs.modal.confirm(operation+'信息','确定'+operation+'信息？', function (index) {
                febs.postArray(ctx + 'hazardExamineRecord', data, function () {
                    layer.closeAll();
                    febs.alert.success('提交成功');
                    $('#febs-hazardExamineRecord').find('#query').trigger('click');
                });
            });
        }

    }

    function getImgData(){
        var imgDatas = $view.find(".imgOne")
        var imgList = [];
        $.each(imgDatas,function (index, item){
            var data = {
                filePath: item.dataset.filepath,
                fileName: item.dataset.filename,
                smallPath: item.dataset.smallpath,
            }
            imgList.push(data);
        })
        return imgList;
    }

});